package com.skydroid.h16

import android.content.Context
import android.content.Intent
import android.net.LocalSocket
import android.net.LocalSocketAddress
import android.os.Bundle
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import com.skydroid.h16.common.Constants
import com.skydroid.h16.databinding.ActivityChangeModeBinding
import com.skydroid.h16.utils.BusinessUtils
import java.io.BufferedInputStream
import java.io.IOException
import java.io.OutputStream
import kotlin.concurrent.thread

class ChangeModeActivity: AppCompatActivity() {
    private var mBind: ActivityChangeModeBinding? = null

    private var localSocket: LocalSocket? = null

    private var mReadThread : ReadThread? = null

    private var mOutputStream: OutputStream? = null

    private var mInputStream: BufferedInputStream? = null

    @Volatile
    var isConnect:Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_change_mode)
        initView()
        openConnect()
    }

    companion object{
        fun start(context: Context){
            context.startActivity(
                Intent(context,
                    ChangeModeActivity::class.java)
            )
        }
    }

    private fun initView(){
        mBind = DataBindingUtil.setContentView(this, R.layout.activity_change_mode)

        mBind?.buttonSave?.setOnClickListener {
            saveParam()
        }
        mBind?.buttonRead?.setOnClickListener {
            readParam()
        }
    }

    /**
     * 保存手型
     */
    private fun saveParam(){
        val bandPos: Int? = mBind?.spinnerHands?.selectedItemPosition
        if (bandPos == null || bandPos == 0) {
            Toast.makeText(
                this,
                R.string.hand_select_prompt,
                Toast.LENGTH_SHORT
            ).show()
            return
        }

        //发送写入指令 fengyingdianzi: + A9 + 2 +  1 + 1 + SUM
        var cmd = ByteArray(Constants.PACKAGE_HEADER_BUF.size +  5)
        var count = Constants.PACKAGE_HEADER_BUF.size
        //写入帧头
        System.arraycopy(Constants.PACKAGE_HEADER_BUF,0,cmd,0,count)
        cmd[count++] = 0xA9.toByte()
        cmd[count++] = 2.toByte()

        var a = 0
        var b = 0
        when(bandPos){
            1->{
                a = 1
                b = 0
            }
            2->{
                a = 0
                b = 1
            }
            3->{
                a = 0
                b = 0
            }
            4->{
                a = 1
                b = 1
            }
        }
        cmd[count++] = a.toByte()
        cmd[count++] = b.toByte()

        cmd[count] = BusinessUtils.getBCC(cmd)
        thread {
            localSocket?.outputStream?.write(cmd)
        }
    }

    /**
     * 读取手型
     */
    private fun readParam(){
        thread{
            //发送读取指令 fengyingdianzi: + A9 + 2 +  R + 1 + SUM
            var cmd = ByteArray(Constants.PACKAGE_HEADER_BUF.size +  5)
            var count = Constants.PACKAGE_HEADER_BUF.size
            //写入帧头
            System.arraycopy(Constants.PACKAGE_HEADER_BUF,0,cmd,0,count)
            cmd[count++] = 0xA9.toByte()
            cmd[count++] = 2.toByte()
            cmd[count++] = 'R'.toByte()
            cmd[count++] = 1.toByte()
            //写入BCC SUM
            cmd[count] = BusinessUtils.getBCC(cmd)

            localSocket?.outputStream?.write(cmd)
        }
    }

    /**
     * 设置UI
     */
    private fun setSpinnerHands(setSelection:Int){
        runOnUiThread {
            mBind?.spinnerHands?.setSelection(setSelection)
        }
    }

    /**
     * 打开连接
     */
    private fun openConnect(){
        thread{
            localSocket = LocalSocket(LocalSocket.SOCKET_DGRAM)
            localSocket?.bind(LocalSocketAddress("uart3app"))
            localSocket?.connect(LocalSocketAddress("uart3endpoint"))

            isConnect = true

            mInputStream =  BufferedInputStream(localSocket?.inputStream)
            mOutputStream = localSocket?.outputStream

            mReadThread = ReadThread()
            mReadThread?.start()
        }
    }

    /**
     * 关闭连接
     */
    private fun closeConnect(){
        isConnect = false
        //关闭读取线程
        mReadThread?.interrupt()
        mReadThread = null

        //关闭连接
        try {
            localSocket?.shutdownInput()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.shutdownOutput()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.inputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        try {
            localSocket?.outputStream?.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }

        localSocket = null

    }

    inner class ReadThread:Thread(){
        override fun run() {
            var buffer = ByteArray(1024)
            try {
                while (!isInterrupted){
                    if (mInputStream == null){
                        return
                    }
                    var len = mInputStream!!.read(buffer)
                    if(len > 0){
                        var tempArray = ByteArray(len)
                        System.arraycopy(buffer,0,tempArray,0,len)
                        received(tempArray)
                    }
                }
            }catch (e:InterruptedException){
                e.printStackTrace()
            }catch (e:IOException){
                e.printStackTrace()
            }
        }
    }


    fun received(datas: ByteArray?) {
        when(datas?.get(Constants.PACKAGE_HEADER_BUF.size)){
            0xA9.toByte()->{
                var tempArray = ByteArray(2)
                System.arraycopy(datas,Constants.PACKAGE_HEADER_BUF.size  + 2,tempArray,0,tempArray.size)
                if(tempArray[0] == 1.toByte() && tempArray[1] == 0.toByte()){
                    //美国手
                    showMsg(getString(R.string.read_successful))
                    setSpinnerHands(1)
                }else if(tempArray[0] == 0.toByte() && tempArray[1] == 1.toByte()){
                    //日本手
                    showMsg(getString(R.string.read_successful))
                    setSpinnerHands(2)
                }else if(tempArray[0] == 0.toByte() && tempArray[1] == 0.toByte()){
                    //反美国手
                    showMsg(getString(R.string.read_successful))
                    setSpinnerHands(3)
                }else if(tempArray[0] == 1.toByte() && tempArray[1] == 1.toByte()){
                    //反日本手
                    showMsg(getString(R.string.read_successful))
                    setSpinnerHands(4)
                }else if(tempArray[0] == 0x4F.toByte() && tempArray[1] == 0x4B.toByte()){
                    //成功
                    showMsg(getString(R.string.save_successful))
                }else if(tempArray[0] == 0x4E.toByte() && tempArray[1] == 0x4F.toByte()){
                    //失败
                    showMsg(getString(R.string.save_failed))
                }
            }
        }
    }

    fun showMsg(str:String){
        runOnUiThread {
            Toast.makeText(this,str,Toast.LENGTH_SHORT).show()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        closeConnect()
    }

}